package com.lry.crawlers.comic.pipeline;

import com.jnewbie.JHtml;
import com.jnewbie.request.JPage;
import com.jnewbie.request.JParam;
import com.lry.crawlers.comic.entity.Comic;
import com.lry.crawlers.comic.entity.ComicChapter;
import com.lry.crawlers.comic.entity.ComicUpdate;
import com.lry.crawlers.comic.service.ComicChapterService;
import com.lry.crawlers.comic.service.ComicService;
import com.lry.crawlers.comic.service.ComicUpdateService;
import com.lry.crawlers.information.service.InformationService;
import com.lry.crawlers.message.entity.Message;
import com.lry.crawlers.message.service.MessageService;
import com.lry.crawlers.util.StringTr;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Component;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class ComicPipeline {
    public static Map<String,Object> cmap = new HashMap<>();
    @Autowired
    ComicService comicService;
    @Autowired
    ComicChapterService comicChapterService;
    @Autowired
    ComicUpdateService comicUpdateService;
    @Autowired
    MessageService messageService;
    @Autowired
    InformationService informationService;
    @Value("${lry.web-url}")
    private String url;




    public boolean process(Map<String,Object> map) {

        //判断数据是否不为空
        if(map!= null) {
            //判断数据类型
            if (map.get("key").equals("comicChapter")){
                boolean is = comic(map);
                if(is) {
                    chapter(map);
                }else {
                    return false;
                }
            }else if(map.get("key").equals("chapter")){
                chapter(map);
            }else if(map.get("key").equals("content")){
                content(map);
            }
        }
        return  true;
    }
    //处理漫画搜索
    public boolean comic(Map<String,Object> map) {
        Comic comic = null;
        String title = (String)  map.get("title");
        String descs = (String)  map.get("descs");
        String author = (String)  map.get("author");
        String comicType =(String)  map.get("comicType");
        String cover = (String)  map.get("cover");
        try {
            //提交封面到web端
            JHtml jHtml = new JHtml();
            jHtml.setTimeOut(10000);
            JParam jParam = new JParam();
            jParam.add("url", cover);
            jParam.add("ftitle",StringTr.TR(title));
            jParam.add("ititle",StringTr.TR(title)+".jpg");
            JPage post = jHtml.setParam(jParam).post(url+"/comic/creation");
            int i = 0;
            while (!(post.getContent()!=null ? post.getContent().contains("成功") : false) && i<3){
                Thread.sleep(2000);
                post = jHtml.setParam(jParam).post(url+"/comic/creation");
                i++;
            }
            if(post.getContent()!=null ? post.getContent().contains("成功") : false){
                cover = StringTr.TR(title)+"/" + StringTr.TR(title) + ".jpg";
            }else {
                cover = "defalult.jpg";
            }
        } catch (Exception e) {
            e.printStackTrace();
            cover = "defalult.jpg";
        }
        String updateTime = (String)  map.get("updateTime");
        String comicId = (String) map.get("comicId");

        Integer id = (Integer) map.get("id");
        comic = new Comic();
        comic.setTitle(title.trim());
        comic.setAuthor(author.trim());
        comic.setCreationTime(new Date());
        comic.setDescs(descs.trim());
        comic.setComicId(comicId);
        comic.setComicType(comicType.trim());
        comic.setCover(cover);
        comic.setComicVariableId(id);
        comic.setUpdateTime(updateTime);

        try {
            //添加到mysql
            int i= comicService.setComic(comic);
            if(i==0){
                messageService.setMessage(new Message("mysql漫画入库失败,comicId:"+comicId,new Date()));
            }else{
                ComicUpdate comicUpdatec = new ComicUpdate();
                comicUpdatec.setComicId(comicId);
                comicUpdatec.setComicVariableId(id);
                comicUpdatec.setUpdateTime((String) map.get("updateTime"));
                String updateUrl = (String) map.get("updateUrl");
                updateUrl = "/" + updateUrl.split("/", 4)[3];
                comicUpdatec.setComicUrl(updateUrl);
                comicUpdatec.setChapterNum(0);
                ComicUpdate comicUpdate = comicUpdateService.getComicUpdate(comicId);
                try {
                    if (comicUpdate == null) {
                        comicUpdateService.setComicUpdate(comicUpdatec);
                    }
                }catch(Exception e){
                    StringWriter sw = new StringWriter();
                    e.printStackTrace(new PrintWriter(sw,true));
                    String infomsg = sw.toString();
                    messageService.setMessage(new Message("漫画更新表入库失败,comicId:"+comicId+" .Extends："+infomsg,new Date()));
                }
                return true;
            }
        }catch (DuplicateKeyException e){
        }catch (Exception e){
            StringWriter sw = new StringWriter();
            e.printStackTrace(new PrintWriter(sw,true));
            String infomsg = sw.toString();
            messageService.setMessage(new Message("漫画入库失败,comicId:"+comicId+" .Extends："+infomsg,new Date()));
        }
        return false;
    }


    //处理漫画章节
    public void chapter(Map<String,Object> map){
        ComicChapter comicChapter = null;
        String title = (String) map.get("title");
        List<String> chapterTitle = (List<String>) map.get("chapterTitle");
        List<String> chapterId = (List<String>) map.get("chapterId");
        String comicId = (String) map.get("comicId");
        List<Integer> sortt = map.get("sortt") !=null ? (List<Integer>) map.get("sortt") : null;
        for (int i =0;i<chapterId.size();i++) {
            comicChapter = new ComicChapter();
            comicChapter.setChapterId(chapterId.get(i));
            comicChapter.setChapterPath(StringTr.TR(title.trim())+"/"+StringTr.TR(chapterTitle.get(i).trim()));
            comicChapter.setComicId(comicId);
            comicChapter.setTitle(chapterTitle.get(i).trim());
            comicChapter.setCreationTime(new Date());
            if(sortt!=null)
                comicChapter.setSortt(sortt.get(i));
            else
                comicChapter.setSortt(i);
            cmap.put(chapterId.get(i),comicChapter);
        }
        try{
            if(map.get("key").equals("chapter")){
                comicService.setupdateTime(new Comic(comicId,(String) map.get("updateTime")));
                comicUpdateService.setComicUpdateUp(new ComicUpdate(comicId, (String) map.get("updateTime")));
            }
        }catch (Exception e){}


    }
    //处理漫画内容
    public void content(Map<String,Object> map){
        List<String> content = (List<String>) map.get("content");
        String chapterId = (String) map.get("chapterId");
        if(content.size()==0){
            content.add("章节异常，请联系管理员处理");
        }
        ComicChapter comicChapter =(ComicChapter) cmap.get(chapterId);
        String chapterPath = comicChapter.getChapterPath();
        String[] split = chapterPath.split("/");
        try {
            //上传内容到web端
            JHtml jHtml = new JHtml();
            JParam jParam = new JParam();
            jParam.add("content", content.toString());
            jParam.add("ctitle",split[0]);
            jParam.add("ititle",split[1]);
            JPage post = jHtml.setParam(jParam).setRetryTime(10000).setTimeOut(300000).post(url+"/comicContent/creation");
            int i = 0;
            while (!(post.getContent()!=null ? post.getContent().contains("成功") : false) && i<3){
                System.out.println(chapterPath+"：上传堵塞，休息一会...");
                Thread.sleep(5000);
                 post = jHtml.post(url+"/comicContent/creation");
                i++;
            }
            if(post.getContent()!=null ? post.getContent().contains("成功") : false){
                chapter(comicChapter.getComicId(),chapterId);
                String infId = (String) map.get("infId");
                String[] inf = infId.split("!!!");
                int o = informationService.updateCount(inf[0], inf[1]);
                if(o==0){
                    Thread.currentThread().interrupt();
                }
            }else {
                messageService.setMessage(new Message("漫画内容上传失败,chapter:"+comicChapter,new Date()));
            }

        }catch (DuplicateKeyException e){
        }catch (Exception e){
            StringWriter sw = new StringWriter();
            e.printStackTrace(new PrintWriter(sw,true));
            String infomsg = sw.toString();
            messageService.setMessage(new Message("漫画内容入库失败,chapter:"+comicChapter+" .Extends："+infomsg,new Date()));
            e.printStackTrace();
        }
        }

    public void chapter(String comicId,String chapterId){
        ComicChapter comicChapter =(ComicChapter) cmap.remove(chapterId);
        try {
            int i = 0;
            try{
            //添加到mysql
                i = comicChapterService.setComicChapter(comicChapter);
            }catch (DuplicateKeyException e){
                i = comicChapterService.setComicChapterUp(comicChapter);
            }
            if(i==0){
                messageService.setMessage(new Message("mysql漫画章节入库失败,chapter:"+comicChapter,new Date()));
            }else {
                comicUpdateService.setComicUpdateAddNum(comicId);
            }
        }catch (DuplicateKeyException e){
        }catch (Exception e){
            StringWriter sw = new StringWriter();
            e.printStackTrace(new PrintWriter(sw,true));
            String infomsg = sw.toString();
            messageService.setMessage(new Message("漫画章节入库失败,chapter:"+comicChapter+" .Extends："+infomsg,new Date()));
        }
    }

}